﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Chilkat;
using System.Text.RegularExpressions;

namespace WebServiceClient
{
    public class AlgorithmExecute
    {
        private static readonly string domain = "localhost";
        private static readonly int port = 88;

        public string Run(string login, string password, string name, List<string> intPar, List<string> floatPar)
        {
            HttpRequest req = new HttpRequest();
            Http http = new Http();

            bool success;
            success = http.UnlockComponent("");

            http.CookieDir = "memory";
            http.SendCookies = true;
            http.SaveCookies = true;

            string html;
            html = http.QuickGetStr("http://" + domain + ":" + port + "/");

            req.UsePost();
            req.Path = "/";
            req.AddParam("l", login);
            req.AddParam("p", password);

            req.AddHeader("Referer", "http://" + domain + ":" + port + "/");

            bool ssl;
            ssl = false;
            HttpResponse resp;
            resp = http.SynchronousRequest(domain, port, ssl, req);

            string index = string.Empty;

            foreach (var item in Form1.algorithms)
            {
                if (item.Name == name)
                    index = item.Id;
            }

            req.Path = "/run.htm?algid=" + index;
            req.RemoveAllParams();
            req.AddParam("name", name);
            for (int i = 0; i < intPar.Count; i++)
            {
                req.AddParam("int_" + i, intPar[i]);
            }

            for (int i = 0; i < floatPar.Count; i++)
            {
                req.AddParam("float_" + i, floatPar[i]);
            }

            resp = http.SynchronousRequest(domain, port, ssl, req);

            string result = getRunMessage(resp.BodyStr);

            return result;
        }

        private string getRunMessage(string str)
        {
            string regExpAlgName = @"(?<=\<span.*>).*?(?=\<\/span\>)";
            Regex regex = new Regex(regExpAlgName);
            Match match = regex.Match(str);
            List<string> tmp = new List<string>();
            while (match.Success)
            {
                tmp.Add(match.Value);
                match = match.NextMatch();
            }
            return tmp.FirstOrDefault();
        }
    }
}
